﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using Microsoft.Ajax.Utilities;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using RechercheEmplois.Models;

namespace RechercheEmplois
{
    public class PostulerController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();
        private UserManager<ApplicationUser> UserManager;

        public PostulerController()
        {
            UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
        }
        // GET: /Postuler/
        public ActionResult Index()
        {
            var postules = db.Postules.Include(p => p.Offre).Include(p => p.Recruiteur);
            return View(postules.ToList());
        }

        // GET: /Postuler/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Postule postule = db.Postules.Find(id);
            if (postule == null)
            {
                return HttpNotFound();
            }
            return View(postule);
        }

        // GET: /Postuler/Create
        public ActionResult Create(int offreID)
        {
            try
            {
                var userId = UserManager.FindById(User.Identity.GetUserId()).Utilisateur.ID;
                var posted = db.Postules.SingleOrDefault(d => d.OffreID == offreID && d.UtilisateurID == userId);
                if (posted != null)
                {
                    ViewBag.Message = "Faire attention! Vous avez postulé cette emploi!";
                }
            }
            catch (Exception)
            {
                
            }


            ViewBag.OffreID = offreID;
            var offre = db.Offres.Find(offreID);
            var postule = new Postule()
            {
                Offre = offre
            };
            return View(postule);
        }

        // POST: /Postuler/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        public ActionResult Create(int offreID, HttpPostedFileBase fileCV, HttpPostedFileBase fileLM, string Commentaire)
        {
            try
            {
                if (fileCV != null && fileLM != null)
                {
                    Offre offre = db.Offres.Find(offreID);
                    string from = "studentjob.applying@gmail.com";
                    using (MailMessage mail = new MailMessage(from, offre.Recruiteur.Email))
                    {
                        mail.Subject = "Student Job Applying Job";
                        mail.Body = Commentaire;
                        string fileNameCV = Path.GetFileName(fileCV.FileName);
                        mail.Attachments.Add(new Attachment(fileCV.InputStream, fileNameCV));
                        string fileNameLM = Path.GetFileName(fileLM.FileName);
                        mail.Attachments.Add(new Attachment(fileLM.InputStream, fileNameLM));
                        SmtpClient smtp = new SmtpClient();
                        smtp.Host = "smtp.gmail.com";
                        smtp.EnableSsl = true;
                        NetworkCredential networkCredential = new NetworkCredential(from, "norabbit");
                        smtp.UseDefaultCredentials = true;
                        smtp.Credentials = networkCredential;
                        smtp.Port = 587;
                        smtp.Send(mail);
                        ViewBag.Message = "Envoi réussi!";
                        var post = new Postule()
                        {
                            Commentaire = Commentaire,
                            CV = fileNameCV,
                            LettreMotivation = fileNameLM,
                            DatePostule = DateTime.Now,
                            OffreID = offreID,
                            UtilisateurID = UserManager.FindById(User.Identity.GetUserId()).Utilisateur.ID
                        };
                        db.Postules.Add(post);
                        db.SaveChanges();
                    }
                }
            }
            catch (Exception)
            {
                ViewBag.Message = "Envoi échoué! Re-vérifier votre informations!";
            }

            ViewBag.OffreID = offreID;
            var of = db.Offres.Find(offreID);
            var postule = new Postule()
            {
                Offre = of
            };
            return View(postule);
        }

        // GET: /Postuler/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Postule postule = db.Postules.Find(id);
            if (postule == null)
            {
                return HttpNotFound();
            }
            ViewBag.OffreID = new SelectList(db.Offres, "ID", "Libelle", postule.OffreID);
            ViewBag.UtilisateurID = new SelectList(db.Utilisateurs, "ID", "Nom", postule.UtilisateurID);
            return View(postule);
        }

        // POST: /Postuler/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include="ID,UtilisateurID,OffreID,DatePostule,CV,LettreMotivation")] Postule postule)
        {
            if (ModelState.IsValid)
            {
                db.Entry(postule).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.OffreID = new SelectList(db.Offres, "ID", "Libelle", postule.OffreID);
            ViewBag.UtilisateurID = new SelectList(db.Utilisateurs, "ID", "Nom", postule.UtilisateurID);
            return View(postule);
        }

        // GET: /Postuler/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Postule postule = db.Postules.Find(id);
            if (postule == null)
            {
                return HttpNotFound();
            }
            return View(postule);
        }

        // POST: /Postuler/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Postule postule = db.Postules.Find(id);
            db.Postules.Remove(postule);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
